import React from 'react'
import ResizeBar from './ResizeBar'
import css from './style.less'
import DragState from './DragState'

export const WrappedTableCtx = React.createContext({});
/*
http://www.thinkcss.com/yanshi/2017/2017080601/  CSS布局table表格可拖拽改变宽度的特效
https://css-tricks.com/almanac/properties/t/table-layout/  table 固定布局的问题
参考 rc-table https://github.com/react-component/table/pull/171
              https://github.com/react-component/table

table-layout: fixed布局设置的宽度才会有效

 // 覆盖当前所选颜色主题的颜色。
    "workbench.colorCustomizations": {
        "editorWarning.foreground": "#dfe2e5",
        "editorError.foreground": "#CE8248",
        "gitDecoration.modifiedResourceForeground": "#8AA4C8"
    },
*/
// 需要一个state,这个state该是什么样子呢,必须的功能
// 1. 存储当前这个resize Handle的信息 { colDataIndex: 'dataIndexName', moveX: 0, offsetX: 0 }
// x的值应该是translate偏移的量或者是拖动的距离？？可能拖动的距离要好一点
// moveX是拖动的距离，还有一个问题需不需要保存element的问题。因为element可能会被移除掉，保存他可能不是一个好的做法

// getBoundingClientRect  获取元素的长宽 包括border
// 现在有一个很麻烦的问题
// use ResizeState.coloumns
function updateObjArrayHelper(arr, index, info) {
  let newArr = arr.map((item) => {
    const { current } = item.colRef;
    const thisColWidth = current.getBoundingClientRect().width;
    return {
      ...item,
      offsetLeft: current.offsetLeft + thisColWidth,
    }
  })
  let needUpdateObj = newArr[index];
  let updateInfo = typeof info === 'function' ? info(needUpdateObj) : info
  let afterUpdatedObj = { ...needUpdateObj, ...updateInfo }
  newArr[index] = afterUpdatedObj
  return newArr
}
function getCanResizeCols(columns) {
  if (!Array.isArray(columns) || columns.length === 0) return []
  const res = [];
  columns.forEach((item, index) => {
    let resizeId = item.onHeaderCell()['data-resize-id']
    if (typeof item.onHeaderCell === 'function' && resizeId) {
      res.push({
        colIndex: index,
        id: resizeId,
        colRef: React.createRef(),
        colDataIndex: item.dataIndex
      })
    }
  })
  return res
}

class WrappedTable extends React.Component {
  constructor(props) {
    super(props)
    // get columns data from ColGroup Component by this.props.children
    const { columns } = React.Children.toArray(this.props.children)[0].props
    console.log(columns)
    this.state = {
      colsInfo: getCanResizeCols(columns)
    }
    this.dragGlobalState = new DragState();
  }
  componentDidMount() {
    setTimeout(() => {
      // console.log('after 2s ', this.state.colsInfo);
      this.setResizeBarPosition()
    }, 0)
    document.addEventListener('mouseup', () => {
      this.dragGlobalState.setDragEnd()
    })
  }
  onMouseMove = (ev) => {
    // console.dir(ev.target)
    if (this.dragGlobalState.isDrag) {
      const { index, startXPos, prevOffsetLeft, prevColWidth } = this.dragGlobalState;
      let diffX = ev.clientX - startXPos
      this.updateColsInfo(index, {
        offsetLeft: prevOffsetLeft + diffX,
        colWidth: prevColWidth + diffX
      })
    }
  }
  setResizeBarPosition = () => {
    const { colsInfo } = this.state
    const newColsInfo = colsInfo.map((item) => {
      const { current } = item.colRef;
      const thisColWidth = current.getBoundingClientRect().width;
      return {
        ...item,
        offsetLeft: current.offsetLeft + thisColWidth,
        colWidth: thisColWidth
      }
    })
    console.log('new RecordInfo ', newColsInfo)
    this.setState({
      colsInfo: newColsInfo
    })
  }
  setRootEleRef = (element) => {
    this.rootEle = element
  }
  updateColsInfo = (index, info) => {
    this.setState({
      colsInfo: updateObjArrayHelper(this.state.colsInfo, index, info)
    })
  }
  render() {
    const { colsInfo } = this.state
    // console.log(React.Children.map(this.props.children, (...args) => { console.log(args) }))
    // console.log(this.props)
    // console.log('to Array toArray ', React.Children.toArray(this.props.children))
    console.log('render render render ===================================')
    return (
      <WrappedTableCtx.Provider value={this.state.colsInfo}>
        <div className={css.wrap} ref={this.setRootEleRef} onMouseMove={this.onMouseMove}>
          <div className="rz-handle-wrap">
            {
              colsInfo.map((item, index) => (
                <ResizeBar
                  key={item.id}
                  id={item.id}
                  index={index}
                  {...item}
                  height={this.rootEle ? this.rootEle.getBoundingClientRect().height : 0}
                />
              ))
            }
          </div>
          <div data-table="resize" className="resize-table-wrap">
            <table {...this.props} />
          </div>
        </div>
      </WrappedTableCtx.Provider>
    )
  }
}

export default WrappedTable
